<?php
class YWSMembership {
    public static function getUserByUsername($username) {
        $row = Yii::app()->db->createCommand()
                ->select()
                ->from(PortalUsers::model()->tableName())
                ->where("username='$username'")
                ->queryRow();
        return $row;
    }
    
    public static function getUserById($id) {
        $row = Yii::app()->db->createCommand()
                ->select()
                ->from(PortalUsers::model()->tableName())
                ->where("id='$id'")
                ->queryRow();
        return $row;
    }
    
    public static function getRoles($user_id) {
        $rows = Yii::app()->db->createCommand()
                ->select()
                ->from(PortalUsersInRoles::model()->tableName())
                        ->where("user_id = '$user_id'")
                ->queryAll();
        return $rows;
    }
    
    public static function createUser($username, $password) {
        PortalUsers::model()->insert(array(
            'username'=>$username,
            'password'=>md5(trim($password))
        ));
    }
    
    public static function deleteUser($username) {
        try {
            PortalUsers::model()->find("username = '$username'")->delete();
        }
        catch (CDbException $ex) {
            throw new CDbException($ex->getMessage());
        }
    }
    
    public static function IsUserExist($username) {
        $row = PortalUsers::model()->findByAttributes(array('username'=>$username));
        if ($row == null) return false;
        else return true;
    }
    
    public static function IsSuper($username) {
        $user = YWSMembership::getUserByUsername($username);
        if ($user) {
            if ($user['is_super'] == 1) return true;
        }
        return false;
    }
}
?>
